package com.david.bluetooth.ble;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.bluetooth.BluetoothDevice;

import com.david.bluetooth.R;
import com.david.bluetooth.util.Util;

public class BeaconScanActivity extends Activity {
//    private BluetoothAdapter mBluetoothAdapter;

    private final ScanCallback scanCallback = new ScanCallback() {// 扫描Callback
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            String hexString = Util.bytesToHex(result.getScanRecord().getBytes());

            // 注意：以下的值可能需要根据你的Beacon设备的实际数据来进行调整
            String uuid = hexString.substring(9, 40);
            String major = hexString.substring(40, 44);
            String minor = hexString.substring(44, 48);

            Log.i("Beacon", "UUID: " + uuid + " Major: " + major + " Minor: " + minor);


            BluetoothDevice device = result.getDevice();
            String deviceAddress = device.getAddress();
            // 这里的deviceAddress就是设备的MAC地址
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();


// 开始扫描
        bluetoothLeScanner.startScan(scanCallback);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().stopScan(scanCallback);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sbuf = new StringBuilder();
        for (int idx = 0; idx < bytes.length; idx++) {
            int intVal = bytes[idx] & 0xff;
            if (intVal < 0x10) sbuf.append("0");
            sbuf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return sbuf.toString();
    }
}
